<?php
namespace app\common\helper;
use think\Env;

class CurlHelper
{
    private $userAgent;
    private $timeout;
    private $referer;

    public function __construct($userAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', $timeout = 10, $referer = "http://XXX")
    {
        $this->userAgent = $userAgent;
        $this->timeout = $timeout;
        $this->referer = $referer;
    }

    public function sendRequest($url, $postFields = '', $cookies = '', $returnCookies = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, $this->userAgent);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, $this->referer);

        if (!empty($postFields)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postFields));
        }

        if (!empty($cookies)) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookies);
        }

        curl_setopt($curl, CURLOPT_HEADER, $returnCookies);
        curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            throw new \Exception('Curl error: ' . curl_error($curl));
        }
        curl_close($curl);

        if ($returnCookies) {
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set-Cookie:([^;]*);/", $header, $matches);
            $info['cookie'] = isset($matches[1][0]) ? trim($matches[1][0]) : '';
            $info['content'] = $body;
            return $info;
        } else {
            return $data;
        }
    }

    public  function curl_post_https($url, $post_data)
    {
        $headers = array();
        $headers[] = "Content-Type:application/json";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//设置请求头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');//使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。(这个加不加没啥影响)
        return curl_exec($curl);
    }

    // 图片上传
    public function UploadImageQrCode($img){
        $saveimgfile_1 = Env::get('root_path').'public/wxcode/';
        $fileimgname = time()."-".rand(1000,9999).".png";
        $filecachs = $saveimgfile_1.$fileimgname;
        $fanhuistr = file_put_contents($filecachs,$img);
        return '/wxcode/'.$fileimgname;
    }
}
